import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/Home.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "home",
    component: HomeView,
  },
  {
    path: "/goods",
    name: "goods",

    component: () =>
      import(/* webpackChunkName: "goods" */ "../views/Goods.vue"),
  },
  {
    path: "/user",
    name: "user",
    component: () => import(/* webpackChunkName: "user" */ "../views/User.vue"),
    redirect: "/user/cart",
    // 子路由 children
    children: [
      {
        path: "cart",
        component: () =>
          import(/* webpackChunkName: "cart" */ "../components/user/Cart.vue"),
      },
    ],
  },
  {
    path: "/order",
    name: "order",

    component: () =>
      import(/* webpackChunkName: "order" */ "../views/Order.vue"),
  },
  {
    path: "/free",
    name: "free",

    component: () =>
      import(/* webpackChunkName: "order" */ "../views/Free.vue"),
  },
  ,
  {
    path: "/details",
    name: "Details",
    component: () =>
      import(/* webpackChunkName: "details" */ "../views/Details.vue"),
  },
  {
    // 404的配置
    path: "*",
    name: "error",
    component: () =>
      import(/* webpackChunkName: "error" */ "../components/Error.vue"),
  },
];

// 路由独享守卫

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch((err) => {});
};

// 路由全局前置守卫
// router.beforeEach((to, from, next) => {
//   // console.log("执行了-beforeEach 全局前置的守卫");
//   // console.log(to, from);
//   // next();
//   if (to.path == "/user") {
//     let token = localStorage.getItem("x-auth-token");
//     // 此时必须要有token
//     if (token) {
//       next(); // next()去到to所对应的路由界面
//     } else {
//       // 提示没有登录
//       store.dispatch("showToast/asyncChanIsShowToast", {
//         msg: "请先登录",
//         type: "danger",
//       });
//     }
//     return; // 需要些return，防止执行完上面的next()，还继续执行下面的next()
//   }

//   // 如果不是去往个人中心的路由，则直接通过守卫，去到to所对应的路由界面
//   next();
// });

export default router;
